import 'package:app/api/delivery/index.dart';
import 'package:app/api/material-pick/material.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class ProcessOutput extends StatefulWidget {
  const ProcessOutput({
    super.key,
  });

  @override
  State<ProcessOutput> createState() => _ProcessOutputState();
}

class _ProcessOutputState extends State<ProcessOutput> {

  //站点码
  String _code = "";

  final FocusNode _firstFocusNode = FocusNode();

  //站点物料清单
  List<dynamic> _list = [];

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });

  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  // 设置值
  void setValue(String key, String value) {
    switch (key) {
      case '_code':
        setState(() => _code = value);
        break;
      default:
        throw Exception("key error");
    }
  }

  //清空按钮
  void clear() {
    setState(() {
      _code = "";
      _list = [];
    });
  }

  /// 根据站点码查询物料清单
  void search() {
    Forms.validate(_formKey!).then((valid){
      MaterialApi.of(context).list(_code).then((res){
        if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
          setState(() => _list = res.data['data']);
        }
      });
    });
  }

  /// 开始配送
  void startDelivery() {
    Forms.validate(_formKey!).then((valid) async {
      if(valid){
        if (_list.isEmpty) {
          Error.of(context).show('未查询到拣配信息，请确认');
          return;
        }
        Confirm.of(context).show('确定要开始配送么', (){
          Navigator.of(context).pop();
          Delivery.of(context).immediately(_list[0]['pickId']).then((res){
            if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
              Success.of(context).show('配送成功，请等待');
              clear();
            }
          });
        });
      }
    });
  }

  /// 跳转
  void go(path, Map<String, Object>? params){
    Navigator.of(context).pushNamed(path, arguments: params);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '工序产出'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Group(
              title: '操作',
              height: 120,
              context: context,
              child: Menu(
                  context: context,
                  items: [
                    MenuItem(
                      icon: const Icon(Icons.add,color: Colors.white,size: 40),
                      text: "物料拣配",
                      color: const Color.fromARGB(255, 154, 204, 109),
                      onTap: ()=> go("/material-pick", {'station': _code}),
                    ),
                    MenuItem(
                      icon: const Icon(Icons.call, color: Colors.white,size: 40),
                      text: "空托呼叫",
                      color: const Color.fromARGB(255, 109, 183, 234),
                      onTap: ()=>go('/empty-pallet-call', {'station': _code}),
                    ),
                    MenuItem(
                      icon: const Icon(Icons.call, color: Colors.white,size: 40),
                      text: "",
                      color: const Color.fromARGB(255, 255, 255, 255),
                    )
                  ]
              ),
            ),
            Group(
              context: context,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Forms(formKey: _formKey, formItem: [
                    FormItem(
                      type: 'input',
                      placeholder: '请扫描站点码',
                      filedName: 'code',
                      focusNode: _firstFocusNode,
                      value: _code,
                      labelWidth: 90,
                      labelText: '站点码：',
                      icon: const Icon(Icons.qr_code_scanner_rounded),
                      iconOnTap: scan,
                      onEntry: (value) => search(),
                      onChange: (value) => setValue('_code', value),
                      rules: const {
                        'code': [
                          {'required': true, 'message': '站点码不能为空'}
                        ]
                      },
                    ),
                  ]),
                  Padding(
                    padding: const EdgeInsets.only(top: 10, right: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(top: 10, right: 5, bottom: 10),
                          child: Button(
                            label: '清空',
                            icon: Icons.delete_forever,
                            onPressed: clear,
                            fontColor: Colors.black,
                            backgroundColor: Colors.white,
                            borderColor:
                            const Color.fromARGB(255, 133, 133, 133),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: ListContainer(
                title: '站点物料清单：',
                length: _list.length,
                children: (index) {
                  return [
                    ListTitle(
                      context: context,
                      label: _list[index]['itemName'],
                    ),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '物料编码：',
                        value: _list[index]['itemCode'],
                      ),
                      HorizontalItem(
                        label: '数量：',
                        value: _list[index]['itemQty'],
                        valueBackground: Colors.lightBlueAccent,
                        fontColor: Colors.white,
                      )
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '托  盘  号：',
                        value: _list[index]['container'],
                        valueBackground: Colors.green,
                        fontColor: Colors.white,
                      ),
                      HorizontalItem(
                        label: '任务号：',
                        value: _list[index]['itemWorkCode'],
                      ),
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '流向：',
                        value: _list[index]['wcName'],
                      ),
                      HorizontalItem(
                        label: '开工时间：',
                        value: _list[index]['nextStartDate'],
                      )
                    ]),
                  ];
                },
              ),
            ),
            SizedBox(
              width: MediaQuery.of(context).size.width,
              child: Padding(
                padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                child: Button(
                  onPressed: () => startDelivery(),
                  label: '开始配送',
                  height: 60,
                  fontSize: 18,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
